// 正则表达式测试工具渲染器
window.RegexTesterRenderer = class RegexTesterRenderer {
    static getHTML() {
        return `
            <h2 class="text-3xl font-bold text-gray-800 mb-6">
                <i data-feather="search" class="w-8 h-8 inline mr-3 text-purple-600"></i>
                正则表达式测试器
            </h2>
            <div class="bg-gray-50 rounded-lg p-4 mb-6">
                <p class="text-gray-600">测试和调试正则表达式，支持实时匹配、替换操作和常用模式库。</p>
            </div>
            
            <!-- 正则表达式输入区域 -->
            <div class="bg-white rounded-xl shadow-sm border p-6 mb-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="edit-3" class="w-5 h-5 inline mr-2"></i>
                    正则表达式
                </h3>
                
                <div class="grid grid-cols-1 lg:grid-cols-4 gap-4 mb-4">
                    <div class="lg:col-span-3">
                        <input 
                            id="regex-pattern" 
                            type="text" 
                            placeholder="输入正则表达式，例如：\\d+|[a-zA-Z]+" 
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent font-mono text-lg"
                        >
                    </div>
                    <div>
                        <input 
                            id="regex-flags" 
                            type="text" 
                            placeholder="标志 (gimuy)" 
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent font-mono"
                            maxlength="10"
                        >
                    </div>
                </div>
                
                <!-- 标志说明 -->
                <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-2 mb-4">
                    <div class="flag-item cursor-pointer px-3 py-2 bg-gray-100 rounded-lg text-center hover:bg-purple-100 transition duration-200" data-flag="g">
                        <div class="font-bold text-purple-600">g</div>
                        <div class="text-xs text-gray-600">全局</div>
                    </div>
                    <div class="flag-item cursor-pointer px-3 py-2 bg-gray-100 rounded-lg text-center hover:bg-purple-100 transition duration-200" data-flag="i">
                        <div class="font-bold text-purple-600">i</div>
                        <div class="text-xs text-gray-600">忽略大小写</div>
                    </div>
                    <div class="flag-item cursor-pointer px-3 py-2 bg-gray-100 rounded-lg text-center hover:bg-purple-100 transition duration-200" data-flag="m">
                        <div class="font-bold text-purple-600">m</div>
                        <div class="text-xs text-gray-600">多行</div>
                    </div>
                    <div class="flag-item cursor-pointer px-3 py-2 bg-gray-100 rounded-lg text-center hover:bg-purple-100 transition duration-200" data-flag="u">
                        <div class="font-bold text-purple-600">u</div>
                        <div class="text-xs text-gray-600">Unicode</div>
                    </div>
                    <div class="flag-item cursor-pointer px-3 py-2 bg-gray-100 rounded-lg text-center hover:bg-purple-100 transition duration-200" data-flag="y">
                        <div class="font-bold text-purple-600">y</div>
                        <div class="text-xs text-gray-600">粘性</div>
                    </div>
                    <div class="flag-item cursor-pointer px-3 py-2 bg-gray-100 rounded-lg text-center hover:bg-purple-100 transition duration-200" data-flag="s">
                        <div class="font-bold text-purple-600">s</div>
                        <div class="text-xs text-gray-600">dotAll</div>
                    </div>
                </div>

                <!-- 常用模式选择器 -->
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">常用模式</label>
                    <select id="common-patterns" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500">
                        <option value="">选择常用正则模式...</option>
                    </select>
                </div>

                <!-- 正则解释 -->
                <div id="regex-explanation" class="hidden bg-blue-50 border-l-4 border-blue-400 p-4 rounded">
                    <h4 class="font-medium text-blue-800 mb-2">正则表达式解释</h4>
                    <div id="explanation-content"></div>
                </div>
            </div>

            <!-- 测试文本区域 -->
            <div class="bg-white rounded-xl shadow-sm border p-6 mb-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="type" class="w-5 h-5 inline mr-2"></i>
                    测试文本
                </h3>
                
                <textarea 
                    id="test-string" 
                    rows="6" 
                    placeholder="输入要测试的文本内容..."
                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent font-mono resize-y"
                ></textarea>
                
                <div class="flex flex-wrap gap-3 mt-4">
                    <button 
                        id="test-regex" 
                        class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="play" class="w-4 h-4 mr-2"></i>
                        测试匹配
                    </button>
                    <button 
                        id="clear-test" 
                        class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="trash-2" class="w-4 h-4 mr-2"></i>
                        清空
                    </button>
                    <button 
                        id="explain-regex" 
                        class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition duration-200 flex items-center"
                    >
                        <i data-feather="help-circle" class="w-4 h-4 mr-2"></i>
                        解释正则
                    </button>
                </div>
            </div>

            <!-- 匹配结果区域 -->
            <div id="match-results" class="bg-white rounded-xl shadow-sm border p-6 mb-6 hidden">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="target" class="w-5 h-5 inline mr-2"></i>
                    匹配结果
                </h3>
                <div id="match-content">
                    <!-- 动态生成匹配结果 -->
                </div>
            </div>

            <!-- 替换功能区域 -->
            <div class="bg-white rounded-xl shadow-sm border p-6 mb-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="edit-2" class="w-5 h-5 inline mr-2"></i>
                    正则替换
                </h3>
                
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-4 mb-4">
                    <input 
                        id="replacement-text" 
                        type="text" 
                        placeholder="替换为... (支持 $1, $2 等引用分组)" 
                        class="px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent font-mono"
                    >
                    <button 
                        id="replace-text" 
                        class="bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-4 rounded-lg transition duration-200 flex items-center justify-center"
                    >
                        <i data-feather="repeat" class="w-4 h-4 mr-2"></i>
                        执行替换
                    </button>
                    <button 
                        id="copy-replaced" 
                        class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-bold py-3 px-4 rounded-lg transition duration-200 flex items-center justify-center"
                    >
                        <i data-feather="copy" class="w-4 h-4 mr-2"></i>
                        复制结果
                    </button>
                </div>

                <!-- 替换结果 -->
                <div id="replace-result" class="hidden">
                    <label class="block text-sm font-medium text-gray-700 mb-2">替换结果</label>
                    <textarea 
                        id="replaced-text" 
                        rows="6" 
                        readonly
                        class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-50 font-mono resize-y"
                    ></textarea>
                </div>
            </div>

            <!-- 实时统计 -->
            <div id="regex-stats" class="bg-white rounded-xl shadow-sm border p-6 hidden">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    <i data-feather="bar-chart-2" class="w-5 h-5 inline mr-2"></i>
                    匹配统计
                </h3>
                <div id="stats-content" class="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <!-- 动态生成统计信息 -->
                </div>
            </div>
        `;
    }

    static init() {
        const patternInput = document.getElementById('regex-pattern');
        const flagsInput = document.getElementById('regex-flags');
        const testStringInput = document.getElementById('test-string');
        const commonPatternsSelect = document.getElementById('common-patterns');
        const testButton = document.getElementById('test-regex');
        const clearButton = document.getElementById('clear-test');
        const explainButton = document.getElementById('explain-regex');
        const replacementInput = document.getElementById('replacement-text');
        const replaceButton = document.getElementById('replace-text');
        const copyReplacedButton = document.getElementById('copy-replaced');
        
        // 初始化常用模式
        this.loadCommonPatterns();
        
        // 标志选择器
        document.querySelectorAll('.flag-item').forEach(item => {
            item.addEventListener('click', (e) => {
                const flag = e.currentTarget.getAttribute('data-flag');
                this.toggleFlag(flag);
            });
        });

        // 实时测试（防抖）
        const debouncedTest = DevToolsUtils.debounce(() => {
            if (patternInput.value.trim() && testStringInput.value.trim()) {
                this.testRegex();
            }
        }, 500);

        patternInput.addEventListener('input', debouncedTest);
        flagsInput.addEventListener('input', debouncedTest);
        testStringInput.addEventListener('input', debouncedTest);

        // 常用模式选择
        commonPatternsSelect.addEventListener('change', (e) => {
            if (e.target.value) {
                const [pattern, flags] = e.target.value.split('|');
                patternInput.value = pattern;
                flagsInput.value = flags || '';
                this.updateFlagButtons();
                if (testStringInput.value.trim()) {
                    this.testRegex();
                }
            }
        });

        // 按钮事件
        testButton.addEventListener('click', () => this.testRegex());
        clearButton.addEventListener('click', () => this.clearAll());
        explainButton.addEventListener('click', () => this.explainRegex());
        replaceButton.addEventListener('click', () => this.replaceText());
        copyReplacedButton.addEventListener('click', () => this.copyReplaced());

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'Enter') {
                e.preventDefault();
                this.testRegex();
            }
        });

        // 初始化示例
        this.loadExample();

        // 初始化 Feather Icons
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 100);
    }

    static loadCommonPatterns() {
        const result = RegexTester.getCommonPatterns();
        if (result.success) {
            const select = document.getElementById('common-patterns');
            result.data.forEach(pattern => {
                const option = document.createElement('option');
                option.value = `${pattern.pattern}|${pattern.flags}`;
                option.textContent = `${pattern.name} - ${pattern.description}`;
                select.appendChild(option);
            });
        }
    }

    static toggleFlag(flag) {
        const flagsInput = document.getElementById('regex-flags');
        let flags = flagsInput.value;
        
        if (flags.includes(flag)) {
            flags = flags.replace(flag, '');
        } else {
            flags += flag;
        }
        
        flagsInput.value = flags;
        this.updateFlagButtons();
        
        // 如果有测试内容，立即重新测试
        const testString = document.getElementById('test-string').value;
        if (testString.trim()) {
            this.testRegex();
        }
    }

    static updateFlagButtons() {
        const flags = document.getElementById('regex-flags').value;
        document.querySelectorAll('.flag-item').forEach(item => {
            const flag = item.getAttribute('data-flag');
            if (flags.includes(flag)) {
                item.classList.add('bg-purple-500', 'text-white');
                item.classList.remove('bg-gray-100', 'hover:bg-purple-100');
            } else {
                item.classList.remove('bg-purple-500', 'text-white');
                item.classList.add('bg-gray-100', 'hover:bg-purple-100');
            }
        });
    }

    static testRegex() {
        const pattern = document.getElementById('regex-pattern').value;
        const flags = document.getElementById('regex-flags').value;
        const testString = document.getElementById('test-string').value;
        
        const result = RegexTester.testRegex(pattern, flags, testString);
        
        if (result.success) {
            this.displayResults(result.data);
            this.displayStats(result.data.stats);
        } else {
            this.displayError(result.error);
        }
    }

    static displayResults(data) {
        const resultsDiv = document.getElementById('match-results');
        const contentDiv = document.getElementById('match-content');
        
        resultsDiv.classList.remove('hidden');
        
        if (data.matches.length === 0) {
            contentDiv.innerHTML = `
                <div class="text-center py-8 text-gray-500">
                    <i data-feather="x-circle" class="w-12 h-12 mx-auto mb-2 text-red-400"></i>
                    <p class="text-lg font-medium">无匹配结果</p>
                    <p>正则表达式未匹配到任何内容</p>
                </div>
            `;
        } else {
            let html = `
                <div class="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg">
                    <div class="flex items-center">
                        <i data-feather="check-circle" class="w-5 h-5 text-green-600 mr-2"></i>
                        <span class="font-medium text-green-800">找到 ${data.matches.length} 个匹配</span>
                    </div>
                </div>
                
                <div class="space-y-3">
            `;
            
            data.matches.forEach((match, index) => {
                html += `
                    <div class="border border-gray-200 rounded-lg p-4">
                        <div class="flex justify-between items-center mb-2">
                            <span class="font-medium text-gray-800">匹配 ${index + 1}</span>
                            <span class="text-sm text-gray-500">位置: ${match.index}-${match.index + match.length}</span>
                        </div>
                        <div class="bg-yellow-100 border border-yellow-300 rounded px-3 py-2 mb-2">
                            <code class="text-yellow-800 font-mono">${this.escapeHtml(match.match)}</code>
                        </div>
                        ${match.groups.length > 0 ? `
                            <div class="mt-2">
                                <div class="text-sm font-medium text-gray-700 mb-1">分组:</div>
                                ${match.groups.map((group, i) => `
                                    <div class="text-sm">
                                        <span class="text-gray-600">组${i + 1}:</span> 
                                        <code class="bg-gray-100 px-2 py-1 rounded text-sm">${this.escapeHtml(group || '')}</code>
                                    </div>
                                `).join('')}
                            </div>
                        ` : ''}
                    </div>
                `;
            });
            
            html += '</div>';
            contentDiv.innerHTML = html;
        }
        
        // 更新 Feather Icons
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 50);
    }

    static displayStats(stats) {
        const statsDiv = document.getElementById('regex-stats');
        const contentDiv = document.getElementById('stats-content');
        
        statsDiv.classList.remove('hidden');
        
        contentDiv.innerHTML = `
            <div class="text-center">
                <div class="text-2xl font-bold text-purple-600">${stats.totalMatches}</div>
                <div class="text-sm text-gray-600">总匹配数</div>
            </div>
            <div class="text-center">
                <div class="text-2xl font-bold text-blue-600">${stats.matchedLength}</div>
                <div class="text-sm text-gray-600">匹配字符数</div>
            </div>
            <div class="text-center">
                <div class="text-2xl font-bold text-green-600">${stats.coverage}</div>
                <div class="text-sm text-gray-600">覆盖率</div>
            </div>
            <div class="text-center">
                <div class="text-2xl font-bold text-gray-600">${stats.testStringLength}</div>
                <div class="text-sm text-gray-600">文本长度</div>
            </div>
        `;
    }

    static displayError(error) {
        const resultsDiv = document.getElementById('match-results');
        const contentDiv = document.getElementById('match-content');
        
        resultsDiv.classList.remove('hidden');
        
        contentDiv.innerHTML = `
            <div class="text-center py-8">
                <i data-feather="alert-triangle" class="w-12 h-12 mx-auto mb-2 text-red-400"></i>
                <p class="text-lg font-medium text-red-600">测试失败</p>
                <p class="text-gray-600">${error}</p>
            </div>
        `;
        
        // 隐藏统计
        document.getElementById('regex-stats').classList.add('hidden');
        
        setTimeout(() => {
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }, 50);
    }

    static explainRegex() {
        const pattern = document.getElementById('regex-pattern').value;
        if (!pattern.trim()) {
            DevToolsUtils.showToast('请输入正则表达式', 'error');
            return;
        }
        
        const result = RegexTester.explainRegex(pattern);
        const explanationDiv = document.getElementById('regex-explanation');
        const contentDiv = document.getElementById('explanation-content');
        
        if (result.success) {
            let html = `<p class="text-blue-700 mb-3">${result.data.summary}</p>`;
            
            if (result.data.explanations.length > 0) {
                html += '<div class="space-y-2">';
                result.data.explanations.forEach(item => {
                    html += `
                        <div class="flex items-center space-x-3 text-sm">
                            <code class="bg-blue-100 text-blue-800 px-2 py-1 rounded font-mono">${this.escapeHtml(item.symbol)}</code>
                            <span class="text-gray-700">${item.meaning}</span>
                        </div>
                    `;
                });
                html += '</div>';
            }
            
            contentDiv.innerHTML = html;
            explanationDiv.classList.remove('hidden');
        } else {
            DevToolsUtils.showToast(result.error, 'error');
        }
    }

    static replaceText() {
        const pattern = document.getElementById('regex-pattern').value;
        const flags = document.getElementById('regex-flags').value;
        const testString = document.getElementById('test-string').value;
        const replacement = document.getElementById('replacement-text').value;
        
        const result = RegexTester.replaceWithRegex(pattern, flags, testString, replacement);
        
        if (result.success) {
            const replaceResultDiv = document.getElementById('replace-result');
            const replacedTextArea = document.getElementById('replaced-text');
            
            replacedTextArea.value = result.data.result;
            replaceResultDiv.classList.remove('hidden');
            
            if (result.data.hasChanges) {
                DevToolsUtils.showToast(`已替换 ${result.data.replacementCount} 处匹配`, 'success');
            } else {
                DevToolsUtils.showToast('未找到需要替换的内容', 'info');
            }
        } else {
            DevToolsUtils.showToast(result.error, 'error');
        }
    }

    static copyReplaced() {
        const replacedText = document.getElementById('replaced-text').value;
        if (!replacedText) {
            DevToolsUtils.showToast('没有替换结果可复制', 'error');
            return;
        }
        
        DevToolsUtils.copyToClipboard(replacedText);
        DevToolsUtils.showToast('替换结果已复制', 'success');
    }

    static clearAll() {
        document.getElementById('regex-pattern').value = '';
        document.getElementById('regex-flags').value = '';
        document.getElementById('test-string').value = '';
        document.getElementById('replacement-text').value = '';
        document.getElementById('common-patterns').value = '';
        
        document.getElementById('match-results').classList.add('hidden');
        document.getElementById('regex-stats').classList.add('hidden');
        document.getElementById('replace-result').classList.add('hidden');
        document.getElementById('regex-explanation').classList.add('hidden');
        
        this.updateFlagButtons();
    }

    static loadExample() {
        document.getElementById('regex-pattern').value = '\\b\\w+@\\w+\\.\\w+\\b';
        document.getElementById('regex-flags').value = 'gi';
        document.getElementById('test-string').value = '联系我们：admin@example.com 或 support@test.org\n技术支持：tech@company.net';
        this.updateFlagButtons();
    }

    static escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
};